﻿package
{
	import flash.desktop.NativeApplication;
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.display.NativeMenu;
	import flash.display.NativeMenuItem;
	import flash.display.NativeWindow;
	import flash.display.NativeWindowInitOptions;
	import flash.display.Screen;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.display.StageDisplayState;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.HTMLUncaughtScriptExceptionEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.NativeWindowBoundsEvent;
	import flash.events.UncaughtErrorEvent;
	import flash.filesystem.File;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.html.HTMLHistoryItem;
	import flash.html.HTMLLoader;
	import flash.media.SoundMixer;
	import flash.media.SoundTransform;
	import flash.net.SharedObject;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.Capabilities;
	import flash.system.IME;
	import flash.system.IMEConversionMode;
	import flash.system.LoaderContext;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	
	[SWF(frameRate = "45", backgroundColor = "#333333", width = "940", height = "610", scriptTimeLimit = "5")]
	public class zmair extends Sprite
	{
		
		private static const HTML_WIDTH:Number = 940;
		
		private static const HTML_HEIGHT:Number = 590;
		
		private static const PAY_WIDTH:Number = 650;
		
		private static const PAY_HEIGHT:Number = 380;
		
		private var html:HTMLLoader;
		
		private var payView:MovieClip;
		
		private var currTopWin:NativeWindow;
		
		[Embed(source = "embed/cfg.json", mimeType = "application/octet-stream")]
		private var _cfgAsset:Class;
		
		[Embed(source = "embed/payView.bin", mimeType = "application/octet-stream")]
		private var _payViewAsset:Class;
		
		private var PayContent:Class;
		
		private const _rootURL:String = " https://www.4399.com/flash/zmhj2.htm";
		
		private var _nativeMenu:NativeMenu;
		
		public function zmair()
		{
			super();
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(evt:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			stage.scaleMode = StageScaleMode.SHOW_ALL;
			stage.nativeWindow.addEventListener(NativeWindowBoundsEvent.MOVE, onMoving);
			stage.nativeWindow.addEventListener(Event.DEACTIVATE, onDeactivate);
			stage.nativeWindow.addEventListener(Event.ACTIVATE, onActivate);
			stage.nativeWindow.addEventListener(Event.CLOSE, onClose);
			if (loaderInfo && loaderInfo.uncaughtErrorEvents)
			{
				loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onAppUncaughtError);
			}
			initWindowMenu();
			initAsset();
			loadWeb();
			setWindowCenter();
			changeIME();
			Log.ClearLog();
		}
		
		/**
		 * 设置半角输入
		 */
		private function changeIME():void
		{
			if (Capabilities.hasIME && IME.isSupported)
			{
				try{
					IME.conversionMode = IMEConversionMode.ALPHANUMERIC_HALF;
				}catch(err:Error){
					
				}
			}
		}
		
		/**
		 * 初始化窗口顶栏
		 */
		private function initWindowMenu():void
		{
			_nativeMenu = new NativeMenu();
			var opt:NativeMenuItem;
			var item:NativeMenuItem;
			
			opt = new NativeMenuItem("网页操作");
			opt.submenu = new NativeMenu();

			item = new NativeMenuItem("返回主页");
			item.addEventListener(Event.SELECT, goToRoot);
			opt.submenu.addItem(item);

			item = new NativeMenuItem("重载网页");
			item.addEventListener(Event.SELECT, reload);
			opt.submenu.addItem(item);
			
			_nativeMenu.addItem(opt);
			//=======================
			
			opt = new NativeMenuItem("账号操作");
			opt.submenu = new NativeMenu();

			item = new NativeMenuItem("退出登录");
			item.addEventListener(Event.SELECT, logout);
			opt.submenu.addItem(item);
			
			_nativeMenu.addItem(opt);
			//=======================
			
			stage.nativeWindow.menu = _nativeMenu;
		}
		
		/**
		 * 初始化资源
		 */
		private function initAsset():void
		{
			OpenNewWindowModel.build(String(new _cfgAsset()));
			var loader:Loader = new Loader();
			var lc:LoaderContext = new LoaderContext();
			lc.allowCodeImport = true;
			var onAssetLoaded:Function = function(evt:Event):void
			{
				evt.target.removeEventListener(Event.COMPLETE, arguments.callee);
				PayContent = evt.currentTarget.applicationDomain.getDefinition("PayContent") as Class;
			}
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onAssetLoaded);
			loader.loadBytes(new _payViewAsset(), lc);
		}
		
		/**
		 * 设置窗口居中
		 */
		private function setWindowCenter():void
		{
			var screenRect:Rectangle = Screen.mainScreen.bounds;
			var stageRect:Rectangle = stage.nativeWindow.bounds;
			stage.nativeWindow.x = screenRect.width / 2 - stageRect.width / 2;
			stage.nativeWindow.y = screenRect.height / 2 - stageRect.height / 2;
		}
		
		protected function onActivate(param1:Event):void
		{
			SoundMixer.soundTransform = new SoundTransform(1);
		}
		
		protected function onDeactivate(param1:Event):void
		{
			SoundMixer.soundTransform = new SoundTransform(0);
		}
		
		protected function onMoving(param1:NativeWindowBoundsEvent):void
		{
			if (currTopWin)
			{
				var windowBounds:Rectangle = stage.nativeWindow.bounds.clone();
				//var centerX:Number = windowBounds.x + windowBounds.width / 2;
				//var centerY:Number = windowBounds.y + windowBounds.height / 2;
				windowBounds.width = 940;
				windowBounds.height = 590;
				var windowTopLeft:Point = stage.nativeWindow.globalToScreen(new Point(0, 0));
				windowBounds.x = windowTopLeft.x;
				windowBounds.y = windowTopLeft.y;
				currTopWin.x = windowBounds.x;
				currTopWin.y = windowBounds.y;
			}
		}
		
		protected function loadWeb():void
		{
			html = new HTMLLoader();
			html.paintsDefaultBackground = false;
			html.userAgent += "|4399.air.wd|4399.zm5.air";
			html.htmlHost = new MyHost(true, false);
			html.load(new URLRequest(_rootURL));
			html.width = HTML_WIDTH;
			html.height = HTML_HEIGHT;
			//html.x = stage.stageWidth - HTML_WIDTH;
			//html.y = stage.stageHeight - HTML_HEIGHT;
			html.addEventListener(Event.COMPLETE, onHTMLLoaded);
			html.addEventListener(Event.HTML_DOM_INITIALIZE, onHTMLParseComplete);
			html.addEventListener(HTMLUncaughtScriptExceptionEvent.UNCAUGHT_SCRIPT_EXCEPTION, onWebJSError);
			stage.addChild(html);
		}
		
		protected function onHTMLLoaded(param1:Event):void
		{
			html.window.openUrl = openUrl;
			html.window.openPay = openPay;
			html.window.goBack = goBack;
			if (!html.window.console) html.window.console = {};
			html.window.console.log = function(...args):*{
				Log.WriteLog("[JS Console]: " + args.join(" "));
			}
		}
		
		protected function onHTMLParseComplete(evt:Event):void
		{
			//html.window.UniLogin.logout();
		}
		
		protected function onWebJSError(evt:HTMLUncaughtScriptExceptionEvent):void
		{
			try
			{
				var str:String = "";
				if (evt.exceptionValue && evt.exceptionValue.name != "SyntaxError")
				{
					for (var key:* in evt.exceptionValue)
					{
						str += key + "=" + evt.exceptionValue[key] + ";";
					}
					Log.WriteLog(str);
				}
			}
			catch (error:Error)
			{
				trace("write log error:" + error);
			}
		}
		
		protected function onAppUncaughtError(evt:UncaughtErrorEvent):void
		{
			Log.WriteLog(evt.toString());
			Log.WriteLog(Error(evt.target).getStackTrace());
		}
		
		private function onClosePay(evt:MouseEvent):void
		{
			if (payView.parent && payView.contains(payView))
			{
				payView.parent.removeChild(payView);
				SimpleButton(payView.btn_close).removeEventListener(MouseEvent.CLICK, onClosePay);
				payView = null;
			}
			if (currTopWin)
			{
				currTopWin.close();
				currTopWin = null;
			}
		}
		
		private function openUrl(url:String):void
		{
			if (url.indexOf("//") == 0)
			{
				url = "https:" + url;
			}
			navigateToURL(new URLRequest(url), "_blank");
		}
		
		private function createPayContent():void
		{
			payView = new PayContent();
			var btn:SimpleButton = payView.btn_close;
			btn.addEventListener(MouseEvent.CLICK, onClosePay);
		}
		
		private function openPay(param1:String = null):void
		{
			if (currTopWin) currTopWin.close();
			try
			{
				var info:Object = JSON.parse(param1);
			}
			catch (e:Error)
			{
				info = {};
			}
			if (!info.username)
			{
				html.window.alert("调用充值面板失败，缺少参数username");
				Log.WriteLog("调用充值面板失败，缺少参数username");
			}
			var payUnion:String = info.pay_union ? info.pay_union : ["0", "0", "0", "10012", "10037", "10049"][info.index || 0];
			var random:Number = Math.ceil(Math.random() * 1000000);
			param1 = "http://cz.4399.com/wpay.html?pay_union=" + payUnion + "&username=" + info.username + "&server=102&role=" + info.role + "&pay_money=10&screen=1&random_num=" + random + "&mark=12&is_wpay=2";
			var rect:Rectangle = stage.nativeWindow.bounds.clone();
			rect.width = HTML_WIDTH;
			rect.height = HTML_HEIGHT;
			var p:Point = stage.nativeWindow.globalToScreen(new Point(0, 0));
			rect.x = p.x;
			rect.y = p.y;
			currTopWin = openNewWindow(rect, param1);
			if (currTopWin)
			{
				createPayContent();
				currTopWin.stage.addChildAt(payView, 0);
			}
		}
		
		private function openNewWindow(param1:Rectangle, param2:String):NativeWindow
		{
			var options:NativeWindowInitOptions = new NativeWindowInitOptions();
			options.maximizable = false;
			options.minimizable = false;
			options.resizable = false;
			options.type = "utility";
			options.systemChrome = "none";
			options.transparent = true;
			options.owner = stage.nativeWindow;
			var loader:HTMLLoader = HTMLLoader.createRootWindow(true, options, false, param1);
			var request:URLRequest = new URLRequest(param2);
			loader.load(request);
			loader.width = PAY_WIDTH;
			loader.height = PAY_HEIGHT;
			loader.x = 145;
			loader.y = 105;
			loader.window.open = openUrl;
			return loader.stage.nativeWindow;
		}
		
		private function goBack():void
		{
			html.load(new URLRequest(html.getHistoryAt(0).url));
		}
		
		private function reload(... args):void
		{
			html.reload();
		}
		
		private function goToRoot(... args):void
		{
			goBack();
		}
		
		private function logout(... args):void
		{
			if (html)
			{
				try{
					html.window.UniLogin.logout();
				}catch(err:Error){
					
				}
			}
		}
		
		protected function onClose(param1:Event):void
		{
			if (currTopWin)
			{
				currTopWin.close();
				currTopWin = null;
			}
			NativeApplication.nativeApplication.exit();
		}
	}
}
